package com.webservice;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread {
	public static final int CLIENT_QUERY_ERROR = 400;
	public static final int FILE_NOT_FOUND = 404;

	private Socket socket;
	private InputStream in;
	private PrintStream out;

	public Processor(Socket socket) {
		this.socket = socket;
		try {
			this.in = socket.getInputStream();
			this.out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		String fileName = pares(in);
		sendFile(fileName);
	}

	public String pares(InputStream in) {
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String fileName = null;
		try {
			String httpMessage = br.readLine();
			String[] content = httpMessage.split(" ");
			if (content.length != 3) {
				sendErrorMessage(Processor.CLIENT_QUERY_ERROR, "Cilent query error!");
				return null;
			}

			System.out.println("code:" + content[0] + ",fileName:" + content[1] + ",http vsersion:" + content[2]);
			fileName = content[1];
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}

	public void sendErrorMessage(int errorCode, String errorMessage) {
		out.println("HTTP/1.0 " + errorCode + errorMessage);
		out.println("content-type: text/html");
		out.println();
		out.println("<html>");
		out.println("<titel>Error Message</title>");
		out.println("<body>");
		out.println("<h1>ErrorCode:" + errorCode + ",Message:" + errorMessage + "</h1>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void sendFile(String fileName) {
		String webRoot = System.getProperty("user.dir") + "\\webapps";
		File file = new File(webRoot + fileName);
		if (!file.exists()) {
			sendErrorMessage(Processor.FILE_NOT_FOUND, "File not found!");
			return;
		}
		try {
			InputStream in = new FileInputStream(file);
			byte[] content = new byte[(int) file.length()];
			in.read(content);
			out.println("HTTP/1.0 200 queryfile");
			out.println("content-length:" + content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
